package com.example.springbootsecurity.demo.integrations.cryptography;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.encrypt.BytesEncryptor;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.security.crypto.encrypt.TextEncryptor;
import org.springframework.security.crypto.keygen.BytesKeyGenerator;
import org.springframework.security.crypto.keygen.KeyGenerators;
import org.springframework.security.crypto.keygen.StringKeyGenerator;
import org.springframework.security.crypto.password.Pbkdf2PasswordEncoder;

import java.util.Base64;

public class Crypto {
    public static void main(String[] args) {
        System.out.println("==Cryptography==");
        encryptor();
        System.out.println("==Key Generator==");
        keyGenerator();
        System.out.println("==Password Encoding==");
        passwordEncoding();
    }

    public static void encryptor(){
        String salt = KeyGenerators.string().generateKey();
        System.out.println("Salt: "+salt);

        BytesEncryptor bytesEncryptor=Encryptors.stronger("password", salt);
        byte[] bytes = bytesEncryptor.encrypt("password".getBytes());
        String encrypted = Base64.getEncoder().encodeToString(bytes);
        System.out.println("BytesEncryptor: "+encrypted);

        TextEncryptor textEncryptor=Encryptors.text("password", salt);
        System.out.println("TextEncryptor: "+textEncryptor.encrypt("password"));
    }

    public static void keyGenerator(){
        BytesKeyGenerator generator = KeyGenerators.secureRandom(16);
        byte[] key = generator.generateKey();
        String encodedKey = Base64.getEncoder().encodeToString(key);
        System.out.println("BytesKeyGenerator: "+encodedKey);

        StringKeyGenerator stringKeyGenerator=KeyGenerators.string();
        String keyStr=stringKeyGenerator.generateKey();
        System.out.println("StringKeyGenerator: "+keyStr);

    }

    public static void passwordEncoding(){
        long startTime = System.nanoTime(); // 记录开始时间

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(10);
        String result = encoder.encode("myPassword");
        System.out.println("BCryptPasswordEncoder: "+result);

        long endTime = System.nanoTime(); // 记录结束时间
        long duration = endTime - startTime; // 计算执行时间（纳秒）
        System.out.println("执行时间: " + duration + " 纳秒");


        Pbkdf2PasswordEncoder pbkdf2PasswordEncoder = Pbkdf2PasswordEncoder.defaultsForSpringSecurity_v5_8();
        String password = pbkdf2PasswordEncoder.encode("myPassword");
        System.out.println("Pbkdf2PasswordEncoder: "+password);
    }
}
